package org.shopen.puremvc.view
{
	
	import flash.events.Event;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	import org.puremvc.as3.utilities.statemachine.StateMachine;
	import org.shopen.puremvc.ApplicationConstants;

	public class ApplicationMediator extends Mediator
	{
		public static const NAME : String = "StudyMediator";
		
		public function ApplicationMediator(viewComponent:Object=null)
		{
			super(ApplicationMediator.NAME, viewComponent);
		}
		
		override public function onRegister():void
		{
			addEventListeners();
		}
		
		override public function getMediatorName():String
		{
			return ApplicationMediator.NAME;
		}
		
		protected virtual function get application() : ShoPaint
		{
			return viewComponent as ShoPaint;
		}
		
		override public function listNotificationInterests():Array
		{
			return [StateMachine.CHANGED];
		}
		
		override public function handleNotification(notification:INotification):void
		{
			var noteName : String = notification.getName();
			switch (noteName)
			{
				case StateMachine.CHANGED:
					handleStateChanged(notification);
					break;
			}
		}
		
		private function addEventListeners() : void
		{
			application.addEventListener(ShoPaint.WELCOMING_WINDOW_CREATED, onWelcomingWindowCreated);
			application.addEventListener(ShoPaint.APPLICATION_ADDED_TO_STAGE, onApplicationAddedToStage);
		}
		
		private function onWelcomingWindowCreated(event : Event) : void
		{
			checkForMediator(ShoPaint.COMPONENT_WELCOME_WINDOW, application.welcomeWindow);
		}
		
		private function onApplicationAddedToStage(event : Event) : void
		{
			checkForMediator(ShoPaint.COMPONENT_APP_STAGE, application.stage);
		}
		
		protected function checkForMediator(childSelector : Number, child : Object):void
        {
            switch (childSelector)
            {
                 case ShoPaint.COMPONENT_WELCOME_WINDOW:
                      if (!facade.hasMediator(WelcomeWindowMediator.NAME))
                         facade.registerMediator(new WelcomeWindowMediator(child));
                      break;
                 case ShoPaint.COMPONENT_APP_STAGE:
                      if (!facade.hasMediator(FullscreenMediator.NAME))
                         facade.registerMediator(new FullscreenMediator(child));
                      break;
                 
            }
        }
        
        protected function handleStateChanged(notification : INotification) : void
        {
        	var type : String = notification.getType();
        	switch (type)
        	{
        		case ApplicationConstants.STATE_WELCOMING_CLOSED:
        			application.viewState = ShoPaint.VIEWSTATE_WELCOMING;
        			break;
        	}
        }
	}
}